package com.laikan.reader.bookreader.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.DeviceUtil;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.bookfriend.activity.LoginActivity;
import com.laikan.reader.bookfriend.activity.RechargePage;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.adapter.RewardAdapterNew;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.BaseListDataBean;
import com.laikan.reader.core.bean.RewardBean;
import com.laikan.reader.core.utils.ActivityUitl;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.core.view.CircleProgressBar;
import com.laikan.reader.core.view.ProgressBar_Modern;
import com.laikan.reader.core.view.SnackBarNotice;
import com.laikan.reader.core.view.TouchSwipeRefreshLayout;
import com.socks.library.KLog;
import com.umeng.analytics.MobclickAgent;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import static com.laikan.reader.R.id.common_swiperefresh;

/**
 * 打赏页
 *
 * @author wxl
 */
@SuppressLint ("HandlerLeak")
public class RewardActivityNew extends BasicActivity implements OnClickListener {

    private TextView title_tv;
    /*显示图标和数字的布局*/
    private int type = 0;
    private String id, bookname, content;
    private ListView reward_list;
    private ArrayList<RewardBean> mRewardDataList;
    private RewardAdapterNew mAdapter;
    private int total;// 返回的数据总数
    private ImageView back_tv;
    Drawable drawable_back_tv;
    private RelativeLayout back_layout, common_loaddata_notice;
    /*只显示数字的布局*/
    private RelativeLayout lin001, lin002, lin003, lin005, lin006, lin007;
    private LinearLayout reward_none, reward_layout;
    private TextView common_prompt_content,common_refresh_net;
    private float y = 0;
    private TouchSwipeRefreshLayout mRewardSwipeRefresh;
    private int mCurrentPage = 1;
    private int END_LIST_PAGE = -1;
    private boolean mIsPullDown = true;// 是否下拉
    private long mLoadMoreInternalTime;
    private ProgressBar_Modern mModernLoadProgressBar;
    private HashSet mRewardIdList = new HashSet();
    private int PAGE_LIMIT_SIZE = 10;
    private String totalSize;
    private EditText reward_content;
    private TextView reward_money, reward_ok, reward_cancel, reward_warn_ok, reward_warn_cancel,tv_warn;
    private AlertDialog rewardDialog;
    private CircleProgressBar circleProgressBar;
    private long mLoadDelaynternalTime;
    private View item_foot_view;

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
//        if(SPUtil.getBoolean("reward_refresh",false)){
//            SPUtil.putBoolean("reward_refresh",false);
//            getData(false);
//        }
     }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void assignViews() {
        setContentView(R.layout.lk_reward);
        reward_none = (LinearLayout)findViewById(R.id.reward_none);
        lin001 = (RelativeLayout)findViewById(R.id.lin001);
        lin002 = (RelativeLayout)findViewById(R.id.lin002);
        lin003 = (RelativeLayout)findViewById(R.id.lin003);
        lin005 = (RelativeLayout)findViewById(R.id.lin005);
        lin006 = (RelativeLayout)findViewById(R.id.lin006);
        lin007 = (RelativeLayout)findViewById(R.id.lin007);
        item_foot_view = LayoutInflater.from(this).inflate(R.layout.item_rewarw_foot_view, null); //脚布局
        reward_list = (ListView)findViewById(R.id.reward_list);
        reward_list.addFooterView(item_foot_view);
        back_tv = (ImageView)findViewById(R.id.iv_back);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        title_tv = (TextView)findViewById(R.id.tv_title);
        mRewardSwipeRefresh = (TouchSwipeRefreshLayout)findViewById(common_swiperefresh);
        mRewardSwipeRefresh.setColorSchemeResources(R.color.C_66ccdd);
        mModernLoadProgressBar = (ProgressBar_Modern)findViewById(R.id.progressbar_modern);
        common_loaddata_notice = (RelativeLayout)findViewById(R.id.common_loaddata_notice);
        common_prompt_content = (TextView)findViewById(R.id.common_prompt_content);
        common_refresh_net = (TextView)findViewById(R.id.common_refresh_net);
        reward_layout = (LinearLayout)findViewById(R.id.reward_layout);
        circleProgressBar = (CircleProgressBar)findViewById(R.id.comon_bgbar_loading);
    }

    @Override
    protected void initData() {
        item_foot_view.setVisibility(View.GONE);
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        back_tv.setImageDrawable(drawable_back_tv);
        id = getIntent().getStringExtra("bookId");
//        bookname = getIntent().getStringExtra("bookName");
//        title_tv.setText(bookname);
        mRewardDataList = new ArrayList<RewardBean>();
        mAdapter = new RewardAdapterNew(mContext, mRewardDataList);
        reward_list.setAdapter(mAdapter);
        mRewardSwipeRefresh.setEnabled(false);
        if (ActivityUitl.isNetworkAvailable(RewardActivityNew.this)) {
            getData(true);
        }else {
            common_prompt_content.setText(R.string.laikan_network_anomaly);
            showLoadFailedView();
        }

    }

    private void getData(boolean flag) {
        if(flag){
            showDialog();
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("type", "1");
        map.put("pageNo", mCurrentPage + "");
        map.put("pageSize", PAGE_LIMIT_SIZE + "");
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                mRewardSwipeRefresh.setRefreshing(false);
                mRewardSwipeRefresh.setLoading(false);
                closeLoadMoreView(System.currentTimeMillis());
                BaseDataBean<BaseListDataBean<RewardBean>> result;
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<BaseListDataBean<RewardBean>>>() {
                }.getType();
                try {
                    reward_layout.setVisibility(View.VISIBLE);
                    common_loaddata_notice.setVisibility(View.GONE);
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (null == result || null == result.getData() || !Constants.RESULT_OK.equals(result.getResult())) {
                        ToastMgr.showShortToast(result.getError_msg());
                        common_prompt_content.setText(R.string.laikan_data_load_failed);
                        closeDelayLoading(System.currentTimeMillis());
                    }else if (null == result.getData().getData() || !(result.getData().getData().size() > 0)) {
                        //                        ptrLv.setPullToRefreshEnabled(false);
                        mRewardSwipeRefresh.setVisibility(View.GONE);
                        reward_none.setVisibility(View.VISIBLE);
                    }else {
                        mRewardSwipeRefresh.setVisibility(View.VISIBLE);
                        reward_none.setVisibility(View.GONE);
                        if (mIsPullDown) {
                            // 下拉刷新
                            mAdapter.setDatas(updateListData(result.getData().getData()));
                        }else {
                            // 上拉加载,数据追加
                          mAdapter.setDatas(loadMoreData(result.getData().getData()));
                        }
                        getCurrentPage(result.getData().getTotal());
                    }
                }catch (Exception e) {
                    common_prompt_content.setText(R.string.laikan_data_load_failed);
                    closeDelayLoading(System.currentTimeMillis());
                    // 数据解析失败
                    if(mIsPullDown){
                        reward_layout.setVisibility(View.GONE);
                        common_loaddata_notice.setVisibility(View.VISIBLE);
                        common_prompt_content.setText(R.string.laikan_data_load_failed);
                        e.printStackTrace();
                    }else{
                        SnackBarNotice.customSnackbarShow(reward_list,R.string.laikan_data_load_failed);
                    }
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                if(mIsPullDown){
                    mRewardSwipeRefresh.setRefreshing(false);
                    mRewardSwipeRefresh.setLoading(false);
                    closeLoadMoreView(System.currentTimeMillis());
                    closeDelayLoading(System.currentTimeMillis());
                    common_prompt_content.setText(R.string.laikan_network_anomaly);
                    KLog.e("网络不给力，请重试。51");
                }else{
                    SnackBarNotice.customSnackbarShow(reward_list,R.string.laikan_network_anomaly);
                }
            }

            @Override
            public void onFinish() {
                dismissDialog();
                common_refresh_net.setOnClickListener(RewardActivityNew.this);
                mRewardSwipeRefresh.setRefreshing(false);
                mRewardSwipeRefresh.setLoading(false);
                closeLoadMoreView(System.currentTimeMillis());
            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_get_reward + id + "?type=1&pageNo=" + mCurrentPage + "&pageSize=10");
//        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpGetRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpGetRequest(APIProtocol.laikan_get_reward + id + "?type=1&pageNo=" + mCurrentPage + "&pageSize=10", null, null, requestListener);
    }

    /**
     * @param totalSize
     */
    public void getCurrentPage(String totalSize) {
        this.totalSize = totalSize;
        mCurrentPage = mRewardDataList.size() / PAGE_LIMIT_SIZE + 1;
        total = Integer.parseInt(PublicUtil.isNum(totalSize));
        if (mRewardDataList.size() >= total) {
            mCurrentPage = END_LIST_PAGE;
        }
    }

    @Override
    protected void setListener() {
        back_layout.setOnClickListener(this);
        lin001.setOnClickListener(this);
        lin002.setOnClickListener(this);
        lin003.setOnClickListener(this);
        lin005.setOnClickListener(this);
        lin006.setOnClickListener(this);
        lin007.setOnClickListener(this);
        common_refresh_net.setOnClickListener(this);
        mRewardSwipeRefresh.setChildView(reward_list);
        mRewardSwipeRefresh.setOnRefreshListener(new TouchSwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mCurrentPage = 1;
                mIsPullDown = true;
                getData(false);
            }
        });

        mRewardSwipeRefresh.setOnLoadListener(new TouchSwipeRefreshLayout.OnLoadListener() {
            @Override
            public void onLoad() {
                mRewardSwipeRefresh.setRefreshing(false);
                if(!ActivityUitl.isNetworkAvailable(mContext)){
                        SnackBarNotice.customSnackbarShow(reward_list,R.string.laikan_network_anomaly);
                        mRewardSwipeRefresh.setLoading(false);
                }else{
                    if(END_LIST_PAGE == mCurrentPage){
//                        SnackBarNotice.customSnackbarShow(reward_list,R.string.fw_data_all_load_done);
                        item_foot_view.setVisibility(View.VISIBLE);
                        mRewardSwipeRefresh.setLoading(false);
                    }else{
                        mModernLoadProgressBar.setVisibility(View.VISIBLE);
                        mLoadMoreInternalTime = System.currentTimeMillis() + 2000;
                        item_foot_view.setVisibility(View.GONE);
                        mIsPullDown = false;
                        getData(false);
                    }
                }
            }
        });
    }

    public void closeLoadMoreView(long currenttime) {
        if (currenttime < mLoadMoreInternalTime) {
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    mModernLoadProgressBar.setVisibility(View.GONE);
                }
            }, 1000);
        }else {
            mModernLoadProgressBar.setVisibility(View.GONE);
        }
    }

    public void closeDelayLoading(long currenttime) {
        if (currenttime < mLoadDelaynternalTime) {
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    showLoadFailedView();
                }
            }, 1000);
        }else {
            showLoadFailedView();
        }
    }

    private void showLoadFailedView() {
        common_refresh_net.setOnClickListener(RewardActivityNew.this);
        reward_layout.setVisibility(View.GONE);
        common_loaddata_notice.setVisibility(View.VISIBLE);
        circleProgressBar.setVisibility(View.INVISIBLE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.common_refresh_net:
                common_refresh_net.setOnClickListener(null);
                mLoadDelaynternalTime = System.currentTimeMillis() + 2000;
                circleProgressBar.setVisibility(View.VISIBLE);
                if(ActivityUitl.isNetworkAvailable(RewardActivityNew.this)){
                    getData(false);
                }else {
                    common_prompt_content.setText(R.string.laikan_network_anomaly);
                    closeDelayLoading(System.currentTimeMillis());
                }
                break;
            case R.id.back_layout:
                finish();
                break;
            case R.id.lin001:
                rewardSubmit("100");
                break;
            case R.id.lin002:
                rewardSubmit("300");
                break;
            case R.id.lin003:
                rewardSubmit("500");
                break;
            case R.id.lin005:
                rewardSubmit("1000");
                break;
            case R.id.lin006:
                rewardSubmit("5000");
                break;
            case R.id.lin007:
                rewardSubmit("10000");
                break;
            default:
                break;
        }
    }
   /**判断是否登录，未登录提示登录*/
    private void rewardSubmit(String count) {
            if (null == SPUtil.getString("user_id", "") || "0".equals(SPUtil.getString("user_id", "")) || "".equals(SPUtil.getString("user_id", ""))) {
                Intent intent = new Intent(this, LoginActivity.class);
                startActivity(intent);
            }else {
                showRewardDialog(count);
            }
    }

    /**
     * 显示选择充值的对话框
     */
    private void showWarnDialog(String warn_content) {
        View view = View.inflate(mContext, R.layout.reward_warn_alterdialog, null);
        tv_warn = (TextView)view.findViewById(R.id.tv_warn);
        reward_warn_ok = (TextView)view.findViewById(R.id.reward_warn_ok);
        reward_warn_cancel = (TextView)view.findViewById(R.id.reward_warn_cancel);
        final AlertDialog mdialog = new AlertDialog.Builder(mContext).setView(view).show();
        tv_warn.setText(warn_content);
        reward_warn_ok.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                mdialog.dismiss();
                Intent intent = new Intent(mContext, RechargePage.class);
                startActivity(intent);
            }
        });
        reward_warn_cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                mdialog.dismiss();
            }
        });
    }

    private ArrayList<RewardBean> updateListData(ArrayList<RewardBean> list) {
        ArrayList<RewardBean> refreshList = new ArrayList<RewardBean>();
        for (int i = 0; i < list.size(); i++) {
            if (!mRewardIdList.contains(list.get(i).getId())) {
                mRewardIdList.add(list.get(i).getId());
                refreshList.add(list.get(i));
            }
        }
        refreshList.addAll(mRewardDataList);
        mRewardDataList.clear();
        mRewardDataList.addAll(refreshList);
        refreshList.clear();
        return mRewardDataList;
    }

    private ArrayList<RewardBean> loadMoreData(ArrayList<RewardBean> list) {
        for (int i = 0; i < list.size(); i++) {
//            if (!mRewardIdList.contains(list.get(i).getId())) {
                mRewardIdList.add(list.get(i).getId());
                mRewardDataList.add(list.get(i));
//            }
        }
        return mRewardDataList;
    }

    private void showRewardDialog(final String item_count) {
        View convertView = View.inflate(mContext, R.layout.reward_alterdialog, null);
        reward_content = (EditText)convertView.findViewById(R.id.reward_content);
        reward_money = (TextView)convertView.findViewById(R.id.reward_money);
        reward_ok = (TextView)convertView.findViewById(R.id.reward_ok);
        reward_cancel = (TextView)convertView.findViewById(R.id.reward_cancel);
        rewardDialog = new AlertDialog.Builder(mContext).setView(convertView).show();
        reward_money.setText(DeviceUtil.getHtmlFormatedString(mContext,R.string.rewardactivity_show_reward_count,item_count));
//        reward_money.setText(item_count + " K币");
        reward_content.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                InputMethodManager imm = ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE));
                if (!hasFocus) {
                    imm.hideSoftInputFromWindow(reward_content.getWindowToken(), 0);
                }
            }
        });
        reward_ok.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                rewardDialog.dismiss();
                submit(item_count);
            }
        });
        reward_cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                rewardDialog.dismiss();
                reward_content.clearFocus();
            }
        });
    }

    private void submit(String count) {
        content = reward_content.getText().toString().trim();
        Map<String, String> map = new HashMap<>();
        map.put("sd", SPUtil.getString("token", ""));
        map.put("type", "1");
        map.put("count", count);
        map.put("content", content);
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                try {
                    JSONObject obj = new JSONObject(httpResponse.responseContent);
                    String result = obj.getString("result");
                    if (obj != null) {
                        if (null == obj.getString("data") || !Constants.RESULT_OK.equals(result)) {
                            if ("102".equals(obj.getString("error_no"))) {
                                String warn = obj.getString("error_msg");
                                showWarnDialog(warn);
                            }
                        }else {
                            if (Constants.RESULT_OK.equals(result)) {
                                mCurrentPage = 1;
                                mIsPullDown = true;
                                SPUtil.putBoolean("reward_refresh", true);
                                mRewardSwipeRefresh.setVisibility(View.VISIBLE);
                                reward_none.setVisibility(View.GONE);
                                getData(true);
                            }
                        }
                    }else {
                        ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    }
                }catch (Exception e) {
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
            }

            @Override
            public void onFinish() {

            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_book_detail_new + id + "/donate?");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_book_detail_new + id + "/donate?", map, null, null, requestListener);
    }
}
